package exp3;

import java.security.interfaces.*;
import java.math.*;
import java.io.*;

//非对称加密-RSA算法3
//使用私钥文件对密文进行解密
public class Dec_RSA {
    public static void main(String args[]) throws Exception {
        //从密文文件Enc_RSA.dat中读取密文，由于保存的只是一行字符串，因此只要一条readLine( )语句即可。
        BufferedReader in = new BufferedReader ( new InputStreamReader ( new FileInputStream ( "Enc_RSA.dat" ) ) );
        String ctext = in.readLine ();
        BigInteger c = new BigInteger ( ctext );
        //从私钥文件Skey_RSA_priv.dat中读取私钥并强制转换为RSAPrivateKey类型
        FileInputStream f = new FileInputStream ( "Skey_RSA_priv.dat" );
        ObjectInputStream b = new ObjectInputStream ( f );
        RSAPrivateKey prk = (RSAPrivateKey) b.readObject ();
        BigInteger d = prk.getPrivateExponent ();
        //获取私钥参数及解密
        BigInteger n = prk.getModulus ();
        System.out.println ( "密文：" + c );
        System.out.println ( "d= " + d );
        System.out.println ( "n= " + n );
        BigInteger m = c.modPow ( d, n );
        //显示解密结果
        System.out.println ( "m= " + m );
        byte[] mt = m.toByteArray ();

        System.out.printf ( "原文：" );
        for (int i = 0; i < mt.length; i++) {
            System.out.print ( (char) mt[i] );
        }
    }
}
